package synchronize;

public class SynchronizedSleepWaitDemo {

    public synchronized void sleepMethod() {
        System.out.println(Thread.currentThread().getName() + ": Sleep start-----");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ": Sleep end-----");
    }

    public synchronized void waitMethod() {
        System.out.println(Thread.currentThread().getName() + ": Wait start-----");
        try {
            //只等待100毫秒而不是无线等待
            wait(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ": Wait end-----");
    }

    public static void main(String[] args) {
        final SynchronizedSleepWaitDemo demo1 = new SynchronizedSleepWaitDemo();

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo1.sleepMethod();
                }
            }).start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-----分割线-----");

        final SynchronizedSleepWaitDemo demo2 = new SynchronizedSleepWaitDemo();

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo2.waitMethod();
                }
            }).start();
        }

    }

}
